﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using EzDesk.Message.Service;
using EzDesk.Utility;
using EzDesk.EzAppApi.Web.Utility.Controllers;
using EzDesk.EzAppApi.Utility;
using EzDesk.EzAppApi.Web.Utility.Attributes;
using EzDesk.EzAppApi.Utility.EzDeskAppApi;
using EzDesk.Message.Model;
using System.Xml.Linq;
using EzDesk.EzAppApi.Utility.Models;
using System.Text;

namespace EzDesk.Message.MobileWeb.Controllers
{
    public class MessageController : EzAppController 
    {
        private TopicService topicService;
        private PersonService personService;

        public MessageController()
        {
            this._apiClient = new EzApiClient();
            this.topicService = new TopicService();
            this.personService = new PersonService();
        }

        [HttpGet]
        [EzDeskAppSessionAuthorize]
        public ActionResult Task(Guid? userId)
        {
            AppTaskCollection taskCollection = new AppTaskCollection();
            taskCollection.AddTask("发布公共消息", "发布一条面向所有人的公共消息", "/message/send");
            taskCollection.AddTask("自定义发送消息", "发布一条自定义消息，可以自由选择消息接受对象", "/message/choosePerson");

            ViewData.Model = taskCollection;
            Response.ContentType = "";
            return new ContentResult()
            {
                ContentType = "text/xml",
                ContentEncoding = Encoding.UTF8,
                Content = taskCollection.ToXmlString(),
            };
        }


        [HttpGet]
        [EzDeskAppSessionAuthorize]
        public ActionResult Index()
        {
        //    ViewData["latestMessages"] = topicService.GetMessages(CurrentUserId, null, 0, 5);
        //    ViewData["sentMessages"] = topicService.GetMessages(null, CurrentUserId, 0, 5);
            return View();
        }

        [HttpGet]
        [EzDeskAppSessionAuthorize]
        public ActionResult Send()
        {
            return View();
        }


        [EzDeskAppSessionAuthorize]
        public ActionResult ChoosePerson(Guid? deptId)
        {
            List<Dept> deptToChooseList = new List<Dept>();
            deptToChooseList.Add(
                new Dept()
                {
                    DeptName = "==所有部门==",
                    Id = Guid.Empty,
                }
                );
            deptToChooseList.AddRange(
                _apiClient.GetAllDepts()
                );

            var deptListSelectItem = new SelectList(
                deptToChooseList,
                "Id",
                "DeptName",
                deptId.GetValueOrDefault(Guid.Empty)
                );

            IList<SimpleUser> usersToChooseList = personService.GetPersonsInDept(deptId);

            ViewData["deptId"] = deptListSelectItem;
            ViewData["usersToChooseList"] = usersToChooseList;
            return View();
        }

        [HttpGet]
        [EzDeskAppSessionAuthorize]
        public ActionResult Show(Guid messageId)
        {
            //todo: 异常处理
            var topic = topicService.GetFullTopic(messageId, CurrentUserId);

            // 判断是否有权限查看

            return View(topic);
        }

        [HttpGet]
        [EzDeskAppSessionAuthorize]
        public ActionResult ReplySingle(Guid messageId)
        {
            var singleMessage = topicService.GetSingleMessage(messageId);

            return View(singleMessage);
        }

        [HttpGet]
        [EzDeskAppSessionAuthorize]
        public ActionResult Confirm(Guid messageId)
        {
            //todo: 异常处理
            var topic = topicService.GetFullTopic(messageId, CurrentUserId);

            return View(topic);
        }





        /// <summary>
        /// 确认一个消息，如果没有返回地址则返回消息本身
        /// </summary>
        /// <param name="messageId">要确认的消息ID</param>
        /// <param name="returnUrl">确认后返回的Url</param>
        /// <returns></returns>
        [EzDeskAppSessionAuthorize]
        public ActionResult ConfirmMessage(Guid messageId)
        {
            try
            {
                topicService.ConfirmMessage(messageId, CurrentUserId);
            }
            catch (Exception ex)
            {
                IErrorLog log = ErrorLog.Instance;
                log.WriteLog(ex, "确认消息错误", 0);
            }

            SetReturnInfoText("成功确认消息。");
            return RedirectToAction("Show", new { messageId = messageId });         
        }



        [HttpPost]
        [EzDeskAppSessionAuthorize]
        public ActionResult SendAdv(IList<string> usersToSend)
        {
            if (usersToSend == null || usersToSend.Count == 0)
            {
                // 没有选择用户，返回继续选择
                SetReturnInfoText("没有选择发送对象");
                return RedirectToAction("ChoosePerson");
            }

            ParticipatorsInfo participators = new ParticipatorsInfo();
            foreach (var userIdStr in usersToSend)
            {
                SimpleUser simpleUser = _apiClient.GetSimpleUserById(new Guid(userIdStr));
                participators.UserParticipators.Add(simpleUser);
            }
            string memberString = usersToSend.Join(",");

            ViewData["participators"] = participators;
            ViewData["memberString"] = memberString;

            return View();
        }
        
        /// <summary>
        /// 发送公共消息
        /// </summary>
        /// <param name="messageText">消息内容</param>
        /// <param name="needConfirm">这个消息是否需要确认</param>
        /// <returns></returns>
        [HttpPost]
        [EzDeskAppSessionAuthorize]
        public ActionResult SendPublicMessage(string messageText, bool needConfirm)
        {
            string memberstring = "everyone";
            Guid senderId = CurrentUserId;
            //todo: 异常处理
            Guid newMessageId = topicService.CreateNewTopic(senderId, messageText, needConfirm, memberstring);

            SetReturnInfoText("新消息发布成功");
            return RedirectToAction("Show", new { messageId = newMessageId });
        }

        [HttpPost]
        [EzDeskAppSessionAuthorize]
        public ActionResult SendAdvMessage(string memberstring, string messageText, bool needConfirm)
        {
            Guid senderId = CurrentUserId;
            //todo: 异常处理
            Guid newMessageId = topicService.CreateNewTopic(senderId, messageText, needConfirm, memberstring);

            SetReturnInfoText("新消息发布成功");
            return RedirectToAction("Show", new { messageId = newMessageId });
        }

        /// <summary>
        /// 回复一个主题
        /// </summary>
        /// <param name="replyText">回复的内容</param>
        /// <param name="topicId">主题ID</param>
        /// <returns></returns>
        [HttpPost]
        [EzDeskAppSessionAuthorize]
        public ActionResult ReplyTopic(string replyText, Guid topicId, bool isReplyToAll)
        {
            Guid senderId = CurrentUserId;
            topicService.ReplyToMessage(senderId, topicId, topicId, replyText, isReplyToAll);

            SetReturnInfoText("回复消息成功");
            return RedirectToAction("Show", new { messageId = topicId });
        }
        
        ///// <summary>
        ///// 想某人发送一条私信
        ///// </summary>
        ///// <param name="targetUserId">目标用户ID</param>
        ///// <param name="messageText">私信消息内容</param>
        ///// <param name="needConfirm">是否需要确认</param>
        ///// <returns></returns>
        //[HttpPost]
        //[EzDeskAppSessionAuthorize]
        //public ActionResult SendPrivateMessage(Guid targetUserId, string messageText, bool needConfirm)
        //{
        //    string memberstring = targetUserId.ToString();
        //    Guid senderId = CurrentUserId;
        //    //todo: 异常处理
        //    Guid newMessageId = topicService.CreateNewTopic(senderId, messageText, needConfirm, memberstring);

        //    SetReturnInfoText("新消息发布成功");
        //    return RedirectToAction("Show", new { messageId = newMessageId });
        //}

        /// <summary>
        /// 回复单条（回复）消息
        /// </summary>
        /// <param name="messageId">被回复的消息ID</param>
        /// <param name="topicId">主题的ID</param>
        /// <param name="messageText">回复的内容</param>
        /// <param name="messageText">是否将回复通知所有人</param>
        /// <returns></returns>
        [HttpPost]
        [EzDeskAppSessionAuthorize]
        public ActionResult ReplySingleMessage(Guid messageId, Guid topicId, string replyText, bool isReplyToAll)
        {
            Guid senderId = CurrentUserId;
            topicService.ReplyToMessage(senderId, messageId, topicId, replyText, isReplyToAll);

            SetReturnInfoText("回复消息成功");
            return RedirectToAction("Show", new { messageId = topicId });
        }






        [HttpGet]
        [EzDeskAppSessionAuthorize]
        public ActionResult FeedTest()
        {
            return View();
        }
    }
}
